package cn.tradewin.pmp.services.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.tradewin.pmp.persist.client.MDeptMapper;
import cn.tradewin.pmp.persist.model.MDept;
import cn.tradewin.pmp.services.DeptManageService;

public class DeptManageServiceImpl implements DeptManageService {

	private final SqlSessionFactory sqlSessionFactory;
	
	public DeptManageServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	public int AddDept(MDept dept) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MDeptMapper mapper = session.getMapper(MDeptMapper.class);
			int iCount = mapper.insertSelective(dept);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}
	

	@Override
	public int updDept(MDept dept) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MDeptMapper mapper = session.getMapper(MDeptMapper.class);
			int iCount = mapper.updateByPrimaryKey(dept);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	public List<MDept> getAllDepts() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MDeptMapper mapper = session.getMapper(MDeptMapper.class);
			return mapper.selectByExample(null);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int DelDepts(List<Integer> depts) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MDeptMapper mapper = session.getMapper(MDeptMapper.class);
			int iDels = mapper.deleteByPrimaryKeyList(depts);
			if (iDels > 0) {
				session.commit();
			}
			return iDels;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public MDept findDeptByPrimary(Integer deptNo) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MDeptMapper mapper = session.getMapper(MDeptMapper.class);
			return mapper.selectByPrimaryKey(deptNo);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}


}
